package es.ibm.santillana.mdm.common.util;

import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;

import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;

public class ValidateXml {
	public static String validateXmlvsXsd(String sFichXml, String sFichXsd)
	{
//	String YES = "yes";
//	String NO = "no";
//	String CHAR_ENCODING = "UTF8";
	boolean NAME_SPACE_AWARE = true;
	boolean VALIDATING = true;
	String SCHEMA_LANGUAGE ="http://java.sun.com/xml/jaxp/properties/schemaLanguage";
	String SCHEMA_LANGUAGE_VAL = "http://www.w3.org/2001/XMLSchema";
	String SCHEMA_SOURCE ="http://java.sun.com/xml/jaxp/properties/schemaSource";

	try
	{
	Reader xmlReader;
	Reader xsdReader;

	xmlReader = new FileReader(sFichXml);
	xsdReader = new FileReader(sFichXsd);

	SAXParserFactory factory = SAXParserFactory.newInstance();

//	 Configure SAXParserFactory to provide parsers that are namespace aware.
	factory.setNamespaceAware(NAME_SPACE_AWARE);
//	 Configure SAXParserFactory to provide parsers that are validating. This property
//	 must have the value true for any of the property strings defined below to take
//	 effect.
	factory.setValidating(VALIDATING);

	SAXParser parser = factory.newSAXParser();

//	 Setting the schema language for xml schema validation
	parser.setProperty(SCHEMA_LANGUAGE, SCHEMA_LANGUAGE_VAL);
//	 Setting the schema source for xml schema validation
	parser.setProperty(SCHEMA_SOURCE, new InputSource(xsdReader));

	DefaultHandler handler = new XmlDefaultHandler();
	parser.parse(new InputSource(xmlReader), handler);
	}
	
	catch (FactoryConfigurationError e) { 
		System.out.println(e.toString());
		
		return e.toString();
	}
	catch (ParserConfigurationException e) { 
		System.out.println(e.toString());
		return e.toString();
	}
	catch (SAXException e) { 
		System.out.println(e.toString());
		return e.toString();
	}
	catch (IOException e) { 
		System.out.println(e.toString());
		return e.toString();
	}

	return "true";
	}


	public static class XmlDefaultHandler extends DefaultHandler
	{
	/** @see org.xml.sax.ErrorHandler#error(SAXParseException)
	*/
	public void error(SAXParseException spe) throws SAXException
	{
	throw spe;
	}

	/** @see org.xml.sax.ErrorHandler#fatalError(SAXParseException)
	*/
	public void fatalError(SAXParseException spe) throws SAXException
	{
	throw spe;
	}
	} 
}
